import axios from 'axios'
import router from '@/router/index.js'
import store from '@/store/index.js'
import { refreshTokenAPI } from '@/api/login.js'

const request = axios.create({
  baseURL: 'http://toutiao.itheima.net'
})

export default ({ method = 'GET', url, params, data, headers, isAuth = true }) =>
  request({
    url: url,
    method: method,
    params: params,
    data: data,
    headers: headers,
    isAuth
  })
request.interceptors.response.use(
  function(response) {
    console.dir(response)
    return response
  },
  async function(error) {
    if (error.response.status === 401) {
      localStorage.removeItem('token')
      const res = await refreshTokenAPI()
      store.commit('setToken', res.data.data.token)

      console.dir(error)
      error.config.headers.Authorization = `Bearer ${res.data.data.token}`
      return request(error.config)
    } else if (error.response.status === 500) {
      store.commit('setToken', '')
      store.commit('setRefresh_Token', '')
      store.commit('setUser', '')
      console.log(router.currentRoute.path)
      router.push(`/login?path=${router.currentRoute.path}`)
    }

    return Promise.reject(error)
  }
)
request.interceptors.request.use(
  function(config) {
    if (store.state.token.length > 0 && config.headers.Authorization === undefined && config.isAuth) {
      config.headers.Authorization = `Bearer ${store.state.token}`
    }
    return config
  },
  function(err) {
    return Promise.reject(err)
  }
)
